import React, { memo, useState, useEffect } from 'react'
import { Pagination } from 'antd'

import { shallowEqualApp, useAppDispatch, useAppSelector } from '@/store'
import { fetchSongCommentAction } from '@/store/modules/song'
import type { FC, ReactNode } from 'react'
import { CommentWrapper, PaginationWrapper } from './style'
import AreaHeader from '@/components/area-header'
import { forMatImageUrl } from '@/utlis/format'

interface IProps {
  children?: ReactNode
  info?: any
}

const Comment: FC<IProps> = (props) => {
  const { info } = props

  const dispatch = useAppDispatch()
  const [page, setPage] = useState(1) // 评论页数
  const [offset, setOffset] = useState(0) // 评论偏移量
  const [limit] = useState(20) // 评论条数

  useEffect(() => {
    // 监听页数变化，改变偏移量
    setOffset((page - 1) * limit)
  }, [page, limit])

  useEffect(() => {
    // 获得评论信息
    const data = {
      id: info?.id,
      limit,
      offset
    }
    dispatch(fetchSongCommentAction(data))
  }, [page, info])

  const { commentTotal, commentList } = useAppSelector(
    (state) => ({
      commentTotal: state.songDetail.commentTotal,
      commentList: state.songDetail.commentList
    }),
    shallowEqualApp
  )


  // 渲染评论列表
  const renderCommentList = () => {
    return (
      commentList?.length > 0 &&
      commentList.map((item) => {
        return (
          <div key={item.commentId} className="comment_item">
            <div className="left">
              <img src={forMatImageUrl(item.user.avatarUrl, 50)} />
            </div>
            <div className="right">
              <div className="user">
                <span className="name">{item.user.nickname}:</span>
                <span className="content">{item.content}</span>
              </div>
              <div className="other_info">
                <span className="time">{item.timeStr}</span>
              </div>
            </div>
          </div>
        )
      })
    )
  }

  // 翻页器页码发生改变
  const pageChange = (page: number) => {
    setPage(page)
  }

  return (
    <CommentWrapper>
      <AreaHeader
        title="评论"
        isRight={false}
        keywords={[`共${commentTotal}条评论`]}
      ></AreaHeader>

      <div className="comment_list">
        <div className="comment_top">
          <span>精彩评论</span>
        </div>
        <div className="comment">{renderCommentList()}</div>
      </div>

      {/* 翻页器 */}
      <PaginationWrapper className='pagination_wrapper'>
        <Pagination current={page} pageSize={limit} defaultCurrent={1} total={commentTotal} showSizeChanger={false} onChange={pageChange}/>
      </PaginationWrapper>

    </CommentWrapper>
  )
}

export default memo(Comment)
